import DisconnectEnable from "./DisconnectEnable";

function onNoParent(instance: Instance, call: (i: Instance) => void) {
    const ac = instance.AncestryChanged.Connect((i, p) => {
        if (!p) {
            ac.Disconnect();
            call(instance)
        }

    })
    return ac
}
/** 实体map */
export default class InstanceMap<K extends Instance, S> {
    instanceMap = new Map<K, S>()
    private disconnectEnable = new DisconnectEnable<K>()

    forEach(call: (value: S, key: K, self: Map<K, S>) => void) {
        return this.instanceMap.forEach(call)
    }
    /** 绑定删除事件回调函数 */
    onRemove(call: (key: K) => void) {
        return this.disconnectEnable.bind(call)
    }
    has(key: K) {
        return this.instanceMap.has(key)
    }
    get(key: K) {
        return this.instanceMap.get(key)
    }
    set(key: K, value: S) {
        if (!this.instanceMap.has(key)) {
            onNoParent(key, () => {
                this.disconnectEnable.fire(key)
                this.instanceMap.delete(key);
            })
        }
        this.instanceMap.set(key, value)
    }
}